package cn.hist.hfp.service;

import cn.hist.hfp.entity.Manager;
import cn.hist.hfp.entity.ManagerValidation;
import cn.hist.hfp.exception.ResourceNotFoundException;
import cn.hist.hfp.repository.ManagerValidationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class ManagerValidationService {

    private final
    ManagerValidationRepository managerValidationRepository;

    private final
    ManagerService managerService;

    @Autowired
    public ManagerValidationService(ManagerValidationRepository managerValidationRepository, ManagerService managerService) {
        this.managerValidationRepository = managerValidationRepository;
        this.managerService = managerService;
    }

    public ManagerValidation findByManagerId(int manager_id) {
        Manager manager = managerService.findOne(manager_id);
        Optional<ManagerValidation> optionalManagerValidation = managerValidationRepository.findTopByManager(manager);
        if (optionalManagerValidation.isPresent()) {
            return optionalManagerValidation.get();
        }
        throw new ResourceNotFoundException();
    }

    public ManagerValidation save(ManagerValidation managerValidation) {
        return managerValidationRepository.save(managerValidation);
    }

    public ManagerValidation update(ManagerValidation managerValidation) {
        return managerValidationRepository.save(managerValidation);
    }

    public void delete(int manager_id) {
        Manager manager = managerService.findOne(manager_id);
        Optional<ManagerValidation> optionalManagerValidation = managerValidationRepository.findTopByManager(manager);
        optionalManagerValidation.ifPresent(managerValidationRepository::delete);
    }
}
